<template>
  <div class="question-detail">
    <div class="page-header">
      <a-button type="text" @click="goBack">
        <icon-arrow-left />返回
      </a-button>
      <h1>问题详情</h1>
    </div>

    <a-spin :loading="loading">
      <!-- 问题详情卡片 -->
      <div class="content-container">
        <div class="main-layout">
          <!-- 左侧主要内容 -->
          <div class="main-content">
            <!-- 问题详情 -->
            <a-card class="question-card">
              <div class="question-header">
                <span class="question-type">{{ question.questionType }}</span>
                <h2 class="question-title">{{ question.title }}</h2>
              </div>
              <div class="question-content">{{ question.content }}</div>
              <div class="question-footer">
                <div class="question-author">
                  <a-avatar :size="32" :style="{ backgroundColor: '#3370ff' }">
                    {{ question.author?.nickname?.charAt(0) || '?' }}
                  </a-avatar>
                  <div class="author-info">
                    <div class="author-name">{{ question.author?.nickname || '匿名用户' }}</div>
                    <div class="publish-time">{{ formatTime(question.publishTime) }}</div>
                  </div>
                </div>
                <div class="question-meta">
                  <div class="question-actions">
                    <a-button type="text" @click="likeQuestion" :loading="likeLoading">
                      <icon-thumb-up :style="{ color: question.isLiked ? '#1890ff' : '' }" />
                      {{ question.likeCount || 0 }}
                    </a-button>
                  </div>
                </div>
              </div>
            </a-card>

            <!-- 回答列表 -->
            <div class="answers-section">
              <div class="section-header">
                <h3>回答 ({{ answers.length }})</h3>
                <a-radio-group v-model="answerSort" type="button">
                  <a-radio value="time">时间排序</a-radio>
                  <a-radio value="likes">点赞排序</a-radio>
                </a-radio-group>
              </div>

              <div class="answer-list">
                <a-card v-for="answer in sortedAnswers" :key="answer.answerId" class="answer-card">
                  <div class="answer-content">{{ answer.content }}</div>
                  <div class="answer-footer">
                    <div class="answer-author">
                      <a-avatar :size="32" :style="{ backgroundColor: '#00b42a' }">
                        {{ answer.replier?.nickname?.charAt(0) || '?' }}
                      </a-avatar>
                      <div class="author-info">
                        <div class="author-name">{{ answer.replier?.nickname || '匿名用户' }}</div>
                        <div class="publish-time">{{ formatTime(answer.publishTime) }}</div>
                      </div>
                    </div>
                    <div class="answer-meta">
                      <span class="publish-time">回答于 {{ formatTime(answer.publishTime) }}</span>
                      <div class="answer-actions">
                        <a-button type="text" @click="likeAnswer(answer)">
                          <icon-thumb-up :style="{ color: answer.isLiked ? '#1890ff' : '' }" />
                          {{ answer.likeCount || 0 }}
                        </a-button>
                        <a-button type="text" @click="replyToAnswer(answer)">
                          <icon-message />回复
                        </a-button>
                      </div>
                    </div>
                  </div>

                  <!-- 回复列表 - 使用递归组件支持多级回复 -->
                  <div v-if="answer.children && answer.children.length > 0" class="reply-list">
                    <ReplyItem 
                      v-for="reply in answer.children" 
                      :key="reply.answerId" 
                      :reply="reply" 
                      :level="1"
                      @like="likeReply"
                      @reply-to="replyToAnswer"
                    />
                  </div>
                </a-card>
              </div>
            </div>
          </div>

          <!-- 右侧发表回答 -->
          <div class="sidebar">
            <a-card class="post-answer-card">
              <template #title>
                <div class="card-title">发表回答</div>
              </template>
              <a-form :model="answerForm" layout="vertical">
                <a-form-item field="content" validate-trigger="blur" :rules="[{ required: true, message: '请输入回答内容' }]">
                  <a-textarea v-model="answerForm.content" placeholder="请输入您的回答..." :auto-size="{ minRows: 4, maxRows: 8 }" />
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="submitAnswer" :disabled="!answerForm.content" :loading="answerLoading">发布回答</a-button>
                </a-form-item>
              </a-form>
            </a-card>
          </div>
        </div>
      </div>
    </a-spin>

    <!-- 回复对话框 -->
    <a-modal
      v-model:visible="replyModalVisible"
      title="回复"
      @ok="submitReply"
      @cancel="cancelReply"
      :ok-button-props="{ disabled: !replyForm.content, loading: replyLoading }"
    >
      <p class="reply-to">回复 {{ replyTo.replier?.nickname || '匿名用户' }}</p>
      <a-textarea v-model="replyForm.content" placeholder="请输入您的回复..." :auto-size="{ minRows: 4, maxRows: 6 }" />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { Message } from '@arco-design/web-vue';
import { questionApi, answerApi } from '@/api/question';
import ReplyItem from '@/components/communication/ReplyItem.vue';

const router = useRouter();
const route = useRoute();
// 确保ID以字符串形式传递，避免JavaScript大整数精度丢失
const questionId = String(route.params.id);

const loading = ref(true);
const likeLoading = ref(false);
const answerLoading = ref(false);
const replyLoading = ref(false);
const question = ref({});
const answers = ref([]);
const answerSort = ref('time');
const replyModalVisible = ref(false);
const replyTo = ref({});

const answerForm = reactive({
  content: ''
});

const replyForm = reactive({
  content: ''
});

// 获取问题详情
const fetchQuestionDetail = async () => {
  loading.value = true;
  try {
    const res = await questionApi.getQuestionDetail(questionId);
    
    if (res.data.success) {
      // 后端返回的数据结构：{success: true, question: {...}, answers: [...]}
      question.value = res.data.question || res.data.data || {};
      answers.value = res.data.answers || [];
    } else {
      Message.error('获取问题详情失败');
      question.value = {};
      answers.value = [];
    }
    
    loading.value = false;
  } catch (error) {
    console.error('获取问题详情失败', error);
    Message.error('获取问题详情失败，请重试');
    question.value = {};
    answers.value = [];
    loading.value = false;
  }
};

// 排序后的回答
const sortedAnswers = computed(() => {
  if (answerSort.value === 'time') {
    return [...answers.value].sort((a, b) => new Date(b.publishTime) - new Date(a.publishTime));
  } else {
    return [...answers.value].sort((a, b) => (b.likeCount || 0) - (a.likeCount || 0));
  }
});

// 返回上一页
const goBack = () => {
  router.back();
};

// 点赞问题
const likeQuestion = async () => {
  likeLoading.value = true;
  try {
    // 切换点赞状态
    const isLiked = !question.value.isLiked;
    
    // 使用questionIdStr或questionId的字符串形式，避免精度丢失
    const questionIdStr = question.value.questionIdStr || String(question.value.questionId);
    const res = await questionApi.likeQuestion(questionIdStr, isLiked);
    
    if (res.data.success) {
      // 更新本地状态
      question.value.isLiked = isLiked;
      question.value.likeCount = isLiked 
        ? (question.value.likeCount || 0) + 1 
        : Math.max((question.value.likeCount || 0) - 1, 0);
      
      Message.success(res.data.message);
    } else {
      Message.error('操作失败，请重试');
    }
  } catch (error) {
    console.error('点赞操作失败', error);
    Message.error('操作失败，请重试');
  } finally {
    likeLoading.value = false;
  }
};

// 点赞回答
  const likeAnswer = async (answer) => {
    try {
      const isLike = !answer.isLiked;
      
      // 使用answerIdStr或answerId的字符串形式，避免精度丢失
      const answerIdStr = answer.answerIdStr || String(answer.answerId);
      const res = await answerApi.likeAnswer(answerIdStr, isLike);
      
      if (res.data.success) {
        // 更新本地状态
        answer.isLiked = isLike;
        answer.likeCount = isLike 
          ? (answer.likeCount || 0) + 1 
          : Math.max((answer.likeCount || 0) - 1, 0);
        
        Message.success(res.data.message);
      } else {
        Message.error('操作失败，请重试');
      }
    } catch (error) {
      console.error('点赞回答失败', error);
      Message.error('操作失败，请重试');
    }
  };

  // 点赞回复
  const likeReply = async (reply) => {
    try {
      const isLike = !reply.isLiked;
      
      // 使用answerIdStr或answerId的字符串形式，避免精度丢失
      const answerIdStr = reply.answerIdStr || String(reply.answerId);
      const res = await answerApi.likeReply(answerIdStr, isLike);
      
      if (res.data.success) {
        // 更新本地状态
        reply.isLiked = isLike;
        reply.likeCount = isLike 
          ? (reply.likeCount || 0) + 1 
          : Math.max((reply.likeCount || 0) - 1, 0);
        
        Message.success(res.data.message);
      } else {
        Message.error('操作失败，请重试');
      }
    } catch (error) {
      console.error('点赞回复失败', error);
      Message.error('操作失败，请重试');
    }
  };

// 回复回答
const replyToAnswer = (answer) => {
  replyTo.value = answer;
  replyModalVisible.value = true;
};

// 提交回复
const submitReply = async () => {
  if (!replyForm.content.trim()) {
    Message.error('请输入回复内容');
    return;
  }
  
  replyLoading.value = true;
  try {
    const replyData = {
      questionId: question.value.questionIdStr || String(question.value.questionId),
      // 使用answerIdStr或answerId的字符串形式，避免精度丢失
      parentAnswerId: replyTo.value.answerIdStr || String(replyTo.value.answerId),
      atUserId: replyTo.value.replier?.userId,
      content: replyForm.content.trim()
    };
    
    const res = await answerApi.createAnswer(replyData);
    
    if (res.data.success) {
      Message.success('回复发表成功');
      replyForm.content = '';
      replyModalVisible.value = false;
      // 重新加载问题详情
      fetchQuestionDetail();
    } else {
      Message.error(res.data.message || '回复发表失败');
    }
  } catch (error) {
    console.error('发表回复失败', error);
    Message.error('发表回复失败，请重试');
  } finally {
    replyLoading.value = false;
  }
};

// 取消回复
const cancelReply = () => {
  replyModalVisible.value = false;
  replyForm.content = '';
};

// 提交回答
const submitAnswer = async () => {
  if (!answerForm.content.trim()) {
    Message.error('请输入回答内容');
    return;
  }
  
  answerLoading.value = true;
  try {
    const answerData = {
      questionId: question.value.questionIdStr || String(question.value.questionId),
      content: answerForm.content.trim()
    };
    
    const res = await answerApi.createAnswer(answerData);
    
    if (res.data.success) {
      Message.success('回答发表成功');
      answerForm.content = '';
      // 重新加载问题详情
      fetchQuestionDetail();
    } else {
      Message.error(res.data.message || '回答发表失败');
    }
  } catch (error) {
    console.error('发表回答失败', error);
    Message.error('发表回答失败，请重试');
  } finally {
    answerLoading.value = false;
  }
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  
  const date = new Date(time);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

onMounted(() => {
  fetchQuestionDetail();
});
</script>

<style scoped>
.question-detail {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.content-container {
  width: 100%;
  max-width: 5400px; /* 从900px增加到5400px，增加6倍 */
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  width: 100%;
  max-width: 5400px; /* 从900px增加到5400px，增加6倍 */
}

.page-header h1 {
  margin: 0 0 0 10px;
  font-size: 24px;
  color: #333;
}

.question-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.question-header {
  margin-bottom: 16px;
}

.question-type {
  display: inline-block;
  padding: 2px 8px;
  background-color: #e8f2ff;
  color: #1890ff;
  border-radius: 4px;
  font-size: 12px;
  margin-bottom: 8px;
}

.question-title {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #333;
}

.question-content {
  margin-bottom: 20px;
  color: #333;
  font-size: 16px;
  line-height: 1.6;
}

.question-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.question-author {
  display: flex;
  align-items: center;
  gap: 10px;
}

.question-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.publish-time {
  color: #999;
  font-size: 14px;
}

.question-actions, .answer-actions, .reply-actions {
  display: flex;
  gap: 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.answer-card {
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.answer-content {
  margin-bottom: 16px;
  color: #333;
  font-size: 16px;
  line-height: 1.6;
}

.answer-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.answer-author {
  display: flex;
  align-items: center;
  gap: 10px;
}

.answer-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.reply-list {
  margin-top: 16px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.reply-item {
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-content {
  margin-bottom: 12px;
  color: #333;
  font-size: 14px;
  line-height: 1.5;
}

.at-user {
  color: #1890ff;
  font-weight: 500;
}

.reply-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reply-author {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.reply-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 6px;
  font-size: 12px;
}

.post-answer-card {
  margin-top: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.reply-to {
  margin-bottom: 12px;
  color: #666;
}
.question-card,
.answer-card,
.post-answer-card {
  width: 100%;
  max-width: 5400px; /* 确保卡片也使用相同的最大宽度 */
}

/* 侧边栏布局样式 */
.main-layout {
  display: flex;
  gap: 24px;
  max-width: 5400px;
  margin: 0 auto;
}

.main-content {
  flex: 1;
  min-width: 0;
}

.sidebar {
  width: 320px;
  flex-shrink: 0;
}

.sidebar .post-answer-card {
  position: sticky;
  top: 20px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .main-layout {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    order: -1;
  }
  
  .sidebar .post-answer-card {
    position: static;
  }
}
</style>